#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import subprocess
import sys
import threading
import json
import time
from pathlib import Path
from typing import Dict, Any, List
# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent))
from common.utils import LogUtil
from common.config import ServiceConfig
from dev_server.device_context import DeviceContext
from dev_server.zmq_server import ZmqServer

logger = LogUtil.get_logger(__name__)

class DeviceContextMgr:
    """设备上下文管理器，负责设备的发现、连接和重试管理"""
    
    def __init__(self, zmq_mgr: ZmqServer, hdc_path: str = None):
        self.__lock = threading.Lock()
        self.__cached_devices = {}
        self.__hdc_path = hdc_path
        self.__zmq_mgr = zmq_mgr
        self.__running = False
        self.__device_scaner = None
        
        # 设备连接机制已修改为始终尝试连接
        
        # 初始化更新线程 
        self.__device_scaner = threading.Thread(target=self.__monitor_devices, daemon=True)

    def destroy(self):
        """销毁设备上下文管理器"""
        self.__running = False
        if self.__device_scaner:
            self.__device_scaner.join()
        logger.info("设备上下文管理器已停止")
        with self.__lock:
            for ctx in self.__cached_devices.values():
                ctx.destroy()
            self.__cached_devices.clear()
        logger.info("设备上下文管理器资源已清理")
    
    def __del__(self):
        """析构函数, 释放资源"""
        self.destroy()
    

    
    def __is_available_sn(self, sn, new_cached_devices, current_time):
        """检查SN是否允许"""
        # 检查是否已存在于上下文中                    
        if self.__cached_devices.get(sn):
            # logger.debug(f"设备{sn}已存在于上下文中，跳过")
            # 从旧缓存中移除, 加入新缓存
            new_cached_devices[sn] = self.__cached_devices.pop(sn)
            return False
        # 始终尝试连接设备
        return True
    
    def __monitor_devices(self):
        """设备更新处理主循环"""
        while self.__running:
            new_cached_devices = {}
            cached_devices_diff = []
            current_time = time.time()
            with self.__lock:
                for sn in self.__list_newest_devices():
                    if not self.__is_available_sn(sn, new_cached_devices, current_time):
                        continue
                    # 尝试创建DeviceContext
                    try:
                        # 创建成功
                        ctx = DeviceContext(sn)
                        cached_devices_diff.append(ctx.get_device_info())
                        new_cached_devices[sn] = ctx
                        logger.info(f"插入设备：{sn}")
                    except Exception as e:
                        logger.error(f"创建DeviceContext失败: {e}")
                # 清理已断开连接的设备
                if self.__cached_devices:
                    for sn, ctx in self.__cached_devices.items():
                        logger.info(f"移除设备：{sn}")
                        cached_devices_diff.append(ctx.get_device_info())
                        ctx.destroy()
                    self.__cached_devices.clear()
                self.__cached_devices = new_cached_devices
            
            if cached_devices_diff:
                # 新旧设备列表的差集不为空说明设备列表有变化，需要通知前端更新设备列表
                logger.info(f"当前全部插入设备: {self.__cached_devices.keys()}")
                logger.info(f"新增和移除的设备: {cached_devices_diff}")
                all_devices = [ctx.get_device_info() for ctx in self.__cached_devices.values()]
                
                logger.info(f"设备事件：name=reload_devices, data={all_devices}")

                self.__zmq_mgr.send_multipart([b"reload_devices", json.dumps(all_devices).encode()])

            # 等待一段时间
            time.sleep(ServiceConfig.DEVICE_SCAN_INTERVAL)
    
    def __list_newest_devices(self):
        """获取当前连接的设备列表"""
        hdc_cmd = self.__hdc_path
        if hdc_cmd is None:
            hdc_cmd = 'hdc'
        try:
            stdout, _ = subprocess.Popen(
                f'{hdc_cmd} list targets',
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            ).communicate()
        except Exception as e:
            logger.error(f"执行 hdc list targets 命令失败: {e}")
            with self.__lock:
                for ctx in self.__cached_devices.values():
                    ctx.destroy()
                self.__cached_devices.clear()
            return []
        # logger.debug(f"hdc list targets 输出:\n{stdout}.")
        sn_list = stdout.splitlines()
        return [sn.strip() for sn in sn_list if sn and sn != '[Empty]']

    def is_alive(self):
        return self.__running

    def start(self):
        """启动设备上下文管理器"""
        self.__running = True
        self.__device_scaner.start()
        logger.info("设备上下文管理器启动成功")
    
    def list_cached_devices(self) -> List[Dict[str, Any]]:
        """获取当前连接的设备列表"""
        device_list = []
        with self.__lock:
            for ctx in self.__cached_devices.values():
                device_list.append(ctx.get_device_info())
        return device_list

    def get_device_context(self, sn: str):
        """获取设备上下文"""
        with self.__lock:
            return self.__cached_devices.get(sn)

    def capture_screen(self, sn: str, filename: str):
        """捕获屏幕"""
        return None